package com.fzg.common.tool;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 公共工具
 *
 * @author fzg
 */
@Slf4j
public class CommonTool {
    /**
     * mapList转为beanList
     *
     * @param mapList       map列表
     * @param beanClass     Bean类型
     * @param isToCamelCase 是否下划线转驼峰
     * @param copyOptions   自定义复制类
     * @return List<T>
     */
    public static <T> List<T> mapListToBeanList(List<Map<String, Object>> mapList, Class<T> beanClass, boolean isToCamelCase, CopyOptions copyOptions) {
        //准备结果
        List<T> list = new ArrayList<>();
        //并行流转换
        mapList.parallelStream().forEachOrdered(item -> list.add(BeanUtil.mapToBean(item, beanClass, isToCamelCase, copyOptions)));
        //返回结果
        return list;
    }

    /**
     * mapList转为beanList
     *
     * @param mapList       map列表
     * @param beanClass     Bean类型
     * @param isToCamelCase 是否下划线转驼峰
     * @return List<T>
     */
    public static <T> List<T> mapListToBeanList(List<Map<String, Object>> mapList, Class<T> beanClass, boolean isToCamelCase) {
        //准备结果
        List<T> list = new ArrayList<>();
        //并行流转换
        mapList.parallelStream().forEachOrdered(item -> list.add(BeanUtil.mapToBean(item, beanClass, isToCamelCase, null)));
        //返回结果
        return list;
    }

    /**
     * mapList转为beanList(默认下划线转驼峰)
     *
     * @param mapList map列表
     * @param beanClass javaBean
     * @return List<T>
     */
    public static <T> List<T> mapListToBeanList(List<Map<String, Object>> mapList, Class<T> beanClass) {
        //准备结果
        List<T> list = new ArrayList<>();
        //并行流转换
        mapList.parallelStream().forEachOrdered(item -> list.add(BeanUtil.mapToBean(item, beanClass, true, null)));
        //返回结果
        return list;
    }

    /**
     * MultipartFile转base64
     *
     * @param file 文件
     * @return String
     * @throws Exception 异常
     */
    public static String test(MultipartFile file) throws Exception {
        BASE64Encoder bEncoder=new BASE64Encoder();
        String[] suffix = Objects.requireNonNull(file.getOriginalFilename()).split("\\.");
        String prefFix="data:image/jpg;base64,".replace("jpg", suffix[suffix.length - 1]);
        return prefFix + bEncoder.encode(file.getBytes()).replaceAll("[\\s*\t\n\r]", "");
    }

}
